import { useRef, useState, useEffect } from 'react';
import { Button, message, Radio, Modal, Table, TablePaginationConfig } from 'antd';
import { ExclamationCircleOutlined, DownloadOutlined } from '@ant-design/icons'
import SearchForm, { SearchRef } from '@src/components/searchForm'
import Year from './components/Year'
import style from '@src/pages/admin/pages/caseManage.module.less'
import { ConditionSchema } from '@src/components/schema/condition'
import { getColumns } from './util'
import { useDispatch } from 'react-redux'
import { caseStatusList } from '@js/config'
import { awaitWrap, confirmAction, formatMoney } from '@src/assets/js/tool'
import { PaginationSchema } from '@src/components/schema/pagination'
import { getCaseListRequest } from './ajax'
import { CaseSchema, PartySchema } from '@src/components/schema/caseSchema'
import moment from 'moment'
import { json2Excel } from '@src/assets/js/excel'

// const extendParams = [
//   { name: 'anotheryear_claim', label: '反请求/变更跨年', component: Year, defaultVisible: true }
// ]

// 处理搜索表单扩展字段
function extendCondition (condition: ConditionSchema[], formData: { [k: string]: any }) {
  const n = formData.anotheryear_claim
  if (n) {
    condition.push({ k: 'anotheryear_claim', o: 'like', v: `%${n}%` })
  }
  return { condition, formData }
}

// 改变搜索条件
function changeCondition (
  d: ConditionSchema[],
  setCondition: (v: ConditionSchema[]) => void,
  setCurrent: (v: number) => void,
) {
  setCondition(d)
  setCurrent(1)
}

// 获取案件状态
function getStatus (status: string) {
  if (status === '全部') {
    return { k: 'status', o: 'not in', v: '未提交,待审核,已提交' }
  }
  return { k: 'status', o: '=', v: status }
}

async function getTableData (
  condition: ConditionSchema[],
  status: string,
  current: number,
  pageSize: number,
  setLoading: (v: boolean) => void,
  setCaseList: (v: CaseSchema[]) => void,
  setTotal: (v: number) => void,
  setTotalMoney: (v: number) => void,
  setTotalCounter: (v: number) => void,
  setTotalCounterMoney: (v: number) => void,
): Promise<void> {
  setLoading(true)
  const c: ConditionSchema[] = [...condition, getStatus(status)]
  const [e, d] = await awaitWrap(getCaseListRequest(c, { current, pageSize }))
  setLoading(false)
  if (e === null && d !== null) {
    setCaseList(d.list.map((li, i) => {
      li.key = pageSize * (current as number - 1) + i + 1
            return li
    }))
    setTotal(d.total)
    setTotalMoney(d.sum_dispute_amount)
    setTotalCounter(d.total_counter)
    setTotalCounterMoney(d.sum_counter_dispute_amount)
  }
}

// 获取当事人字符串
function getPersonString (list: PartySchema[]) {
  const res: string[] = []
  list.forEach(li => {
    const arr = [li.name]
    try {
      const o = JSON.parse(li.tag)
      arr.push(` - ${o.subject_type_tag}`)
    } catch (e) {}
    if (!li.status) {
      arr.push('（终结）')
    }
    res.push(arr.join(''))
  })
  return res.join('、')
}

async function downloadExcel (
  condition: ConditionSchema[],
  status: string,
) {
  const current = 1
  const pageSize = 1000000
  const hide = message.loading('导出中', 120)
  const c: ConditionSchema[] = [...condition, getStatus(status)]
  const [e, d] = await awaitWrap(getCaseListRequest(c, { current, pageSize }))
  hide()
  if (e === null && d !== null) {
    const list = d.list.map((l, i) => {
      const caseno: string = l.caseno_desc || l.case_no || l.acceptno_desc || l.acceptno
      const date1: string = moment(l.docket_datetime * 1000).format('YYYY-MM-DD')
      const date2: string = moment(l.arbitrator_assign_datetime * 1000).format('YYYY-MM-DD')
      const date3: string = moment(l.closure_datetime * 1000).format('YYYY-MM-DD')
      return {
        序号: pageSize * (current - 1) + i + 1,
        案号: caseno + (l.delay_day ? '(缓)' : ''),
        申请人: getPersonString(l.applicants || []),
        被申请人: getPersonString(l.respondents || []),
        案由: l.cause_action,
        争议金额: l.dispute_amount || 0,
        仲裁费: l.fee || 0,
        办案秘书: l.processer,
        立案时间: date1 ? moment(date1).toDate() : '',
        组庭时间: date2 ? moment(date2).toDate() : '',
        结案时间: date3 ? moment(date3).toDate() : '',
        案件区域分类: l.party_area_tag,
        申请人所在地: l.applicant_area,
        被申请人所在地: l.respondent_area,
        仲裁程序: l.procedure,
        仲裁庭组成: l.arbitrators,
        结案方式: l.closure_type
      }
    })
    json2Excel([{ data: list, sheetname: '全委案件' }], '全委案件')
  }
}

interface Props {
  title: string
}

function Main ({ title, ...args }: Props) {
  const searchRef = useRef<SearchRef>(null)
  const [status, setStatus] = useState('全部')
  const [caseList, setCaseList] = useState<CaseSchema[]>([])
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: total => `共 ${total} 条记录`,
    size: 'small'
  })
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [totalMoney, setTotalMoney] = useState(0)
  const [totalCounter, setTotalCounter] = useState(0)
  const [totalCounterMoney, setTotalCounterMoney] = useState(0)
  const [condition, setCondition] = useState<ConditionSchema[]>([])
  const [loading, setLoading] = useState(false)
  const dispatch = useDispatch()
  const columns = getColumns(status, dispatch)
  useEffect(() => {
    getTableData(condition, status, current, pageSize, setLoading, setCaseList, setTotal, setTotalMoney, setTotalCounter, setTotalCounterMoney)
  }, [condition, status, current, pageSize])
  useEffect(() => {
    setPagination({
      current,
      pageSize,
      total,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    })
  }, [current, pageSize, total])
  return (
    <div className={style.container}>
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <SearchForm ref={searchRef} extendCondition={(c, f) => extendCondition(c, f)} onChange={d => changeCondition(d, setCondition, setCurrent)} />
      <div className={style['download-btn-line']}>
        <Button type='primary' ghost onClick={() => confirmAction('您确定要导出excel吗？', () => { downloadExcel(condition, status) })} icon={<DownloadOutlined />}>导出excel</Button>
        {/* <Radio.Group value={status} onChange={v => {setStatus(v.target.value)}}>
          <Radio.Button value='全部'>全部</Radio.Button>
          <Radio.Button value='视为未申请'>视为未申请</Radio.Button>
          <Radio.Button value='不予受理'>不予受理</Radio.Button>
          {caseStatusList.map(li => <Radio.Button value={li} key={li}>{li}</Radio.Button>)}
        </Radio.Group> */}
      </div>
      <div className={style['table-btns-line']}>
        <span className={style['table-total']}>
          <span>总案件数 {pagination.total} 件 / 标的 {formatMoney(totalMoney) || 0} 元 / 反请求案件数： {totalCounter} 件 / 反请求标的：{formatMoney(totalCounterMoney)} 元</span>
        </span>
      </div>
      <div className={style['table-container']}>
        <Table loading={loading} columns={columns} dataSource={caseList} pagination={pagination} onChange={(d) => {
          setCurrent(d.current || 1)
          setPageSize(d.pageSize || 10)
        }} />
      </div>
    </div>
  )
}

export default Main
